import importlib

from src.custom_logger import CustomLogger


class LeetCodeScraper:
    def __init__(self, requests_manager):
        self.requests_manager = requests_manager
        self.logger = CustomLogger()

    def run(self, config):
        operations = config['operations']
        self.logger.info(f"operations: {operations}")
        for operation_config in operations:
            operation_name = operation_config['name']
            self.logger.info(f"operation_name: {operation_name}")
            operation_class = self.get_operation_class(operation_name)
            if operation_class and operation_config.get('methods'):
                operation_instance = operation_class(self.requests_manager, params=operation_config.get('params'))
                self.execute_methods(operation_instance, operation_config)
            else:
                self.logger.info(f"Operation '{operation_name}' is not recognized.")

    def execute_methods(self, operation_instance, operation_config):
        for method_name, method_params in operation_config['methods'].items():
            method = getattr(operation_instance, method_name, None)
            self.logger.info(f"method_name: {method_name}")
            if callable(method):
                if method_params or method_params == {}:
                    method(**method_params) if isinstance(method_params, dict) else method(*method_params)
                else:
                    method()


    def get_operation_class(self, operation_name):
        try:
            module = importlib.import_module('src.operations.' + operation_name)
            return getattr(module, operation_name)
        except (ImportError, AttributeError):
            return None
